// pages/message/add/add.js
const util = require("../../../utils/util")
Page({
  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  getValue(e){
console.log(e);
    this.setData({
      inputValue:e.detail.value
    })
    this.getdata()
  },
  serch(){
    let that = this;
    wx.cloud.database().collection('chat_user').where({
      num: Number(that.data.inputValue)
    }).get().then(({data:res})=>{
      console.log(res);
      that.setData({
        userList: res
      })
      console.log(res._id);
      console.log(res[0]._id);
      const _ = wx.cloud.database().command
      wx.cloud.database().collection('chat_record').where(    
        _.or([
          {
            userA_id : that.data.userInfoA._id,
            userB_id:res[0]._id
          },
          {
            userB_id : that.data.userInfoA._id,
            userA_id:res[0]._id
          }
        ])
      ).get().then(res=>{ console.log(res); 
      if(res.data.length ===0){
         that.setData({
        isaddFriend: true
      }) }
        else{
          that.setData({
            iszFriend:true
          })
          if(res.data[0].friend_status ===1){//有记录了
            that.setData({
              isxFriend:true
            })
          }else if(res.data[0].friend_status ===0){
            that.setData({
              isyFriend: false
            })
          }
        }
      } )
    })

  },
  //我的信息
  getdata(){
    let that = this;
    let _id = wx.getStorageSync('istokenid')
    wx.cloud.database().collection('chat_user').doc(
      _id
    ).get().then(res=>{
      console.log(res);
      that.setData({
        userInfoA:res.data
      })
    })
  },
  //申请加入
  addbnt(e){
    console.log(e);
    let index = e.currentTarget.dataset.index
    let that = this;
    //判断有没有
 console.log(that.data.userList[index]);
    //增加
    wx.cloud.database().collection('chat_record').add({
      data:{
        userA_id:that.data.userInfoA._id,
        userA_faceImg: that.data.userInfoA.faceImg,
        userA_nickName: that.data.userInfoA.nickName,
        userB_id: that.data.userList[index]._id,
        userB_faceImg: that.data.userList[index].faceImg,
        userB_nickName: that.data.userList[index].nickName,
        RECORD:[], //聊天记录
        friend_status:0, //0申请中 1已经好友
        time:util.formatTime(new Date())
      }
    }).then(res=>{
      console.log(res);
      wx.showToast({
        title: '申请成功',
      })

      wx.navigateBack({
        delta:1,
        success(){

        }
      })
    })
  }
})